import uiautomator2 as u2
import time
import subprocess
import os
import requests

d = u2.connect()
# 请求URL
url = "http://127.0.0.1:5000/start_logging"
headers = {
    'Content-Type': 'application/json'
}
app_names = ["家常味典","跃动足迹","新手厨艺宝"]

for app_name in app_names:
    data = {
        "brand": "mi",
        "testname": "test1",
        "case": "test_case5",
        "rpk_name": app_name
    }
    response = requests.post(url, json=data, headers=headers)
    print(f"\n开始处理应用: {app_name}")
    # 初始页面操作
    demo_element = d(description="demo")
    demo_element.click()

    goto_element = d(text="应用跳转")
    goto_element.click()

    search_element = d(text="搜索应用名")
    search_element.click()

    d.send_keys(app_name)
    time.sleep(3)

    jm_element = d(text="加密")
    jm_element.click()
    time.sleep(2)

    open_element = d(text="打开应用")
    open_element.click()
    time.sleep(2)

    try:
        allow_element = d(text="始终允许")
        if allow_element.wait(timeout=3.0):  # 等待3秒，超时则认为元素不存在
            allow_element.click()
            print("权限弹窗已处理")
    except Exception as e:
        print(f"未检测到权限弹窗: {e}")

    try:
        qd_element = d(text="确定")
        if qd_element.wait(timeout=3.0):  # 等待3秒，超时则认为元素不存在
            qd_element.click()
            print("权限弹窗已处理")
    except Exception as e:
        print(f"未检测到权限弹窗: {e}")
    time.sleep(7)  # 等待应用完全启动

    # 获取屏幕尺寸
    width, height = d.window_size()

    # 第一屏广告点击
    x = width * 0.509
    y = height * 0.760

    #全面屏时的坐标
    # start_x = width // 2  # 屏幕横向中心
    # bottom_start_y = height * 0.9  # 从屏幕底部90%位置开始
    # mid_end_y = height * 0.3  # 滑动到屏幕30%位置（更高的位置确保触发）

    print("开始验证第一屏广告点击")
    time.sleep(6)
    d.click(x, y)

    # 等待应用切换或超时
    timeout = 30  # 设置最大等待时间为30秒
    start_time = time.time()
    click_count = 1  # 初始化点击计数

    while True:
        elapsed_time = time.time() - start_time
        current_activity = d.app_current()
        package = current_activity['package']
        activity = current_activity['activity']
        # 检查是否切换到目标应用
        if (package == 'com.miui.hybrid' or activity == 'com.miui.hybrid.VendorLauncherActivity$Launcher1'):
            click_count += 1
            d.click(x, y)
            time.sleep(6)

        # 检查是否超时
        if elapsed_time > timeout or package != 'com.miui.hybrid':
            print(f"等待超时({timeout}秒)，或者已经跳转到其他应用")
            break

    # 应用切换操作
    d.keyevent('KEYCODE_APP_SWITCH')
    time.sleep(3)

    d.click(width * 0.737, height * 0.524)
    time.sleep(3)

    #全面屏时滑动
    # d.swipe(start_x, height - 10, start_x, height // 4, 0.5)


    # 第二屏验证ONhide拉回
    print("开始验证第二屏ONhide拉回")
    d.keyevent('KEYCODE_APP_SWITCH')
    time.sleep(3)
    d.keyevent('KEYCODE_APP_SWITCH')
    # close_button =d(text="关闭")
    # close_button.click()
    time.sleep(2)
    print("第二屏ONhide拉回完成")

    # 第三屏验证点击非广告区域
    print("开始验证第三屏点击非BUTTON区域")
    x1 = width * 0.5
    y1 = height * 0.519
    d.click(x1, y1)
    print("第三屏点击非BUTTON验证完成")
    time.sleep(6)

    # 第四屏验证退出弹框和APL上限
    print("第四屏验证退出弹框和APL上限")
    d.press('back')
    time.sleep(6)


    confirm_element = d(text="确定")
    confirm_element.click()
    print("退出确认弹窗已处理")

    # 新增逻辑：点击确认后等待4秒，检查是否回到桌面
    time.sleep(2)
    current_activity = d.app_current()
    print(current_activity)
    if package == 'com.miui.home':
        print("第四屏验证退出弹框和APL上限完成")
        # 直接清理搜索框
        demo_element = d(description="demo")
        demo_element.click()
        search_element1 = d(text=app_name)
        search_element1.click()
        search_element1.clear_text()
        d.press('home')
        url = "http://127.0.0.1:5000/stop_logging"
        response = requests.post(url)

    else:
        print("未回到桌面，执行应用切换操作")
        time.sleep(2)
        d.keyevent('KEYCODE_APP_SWITCH')
        time.sleep(2)
        d.click(width * 0.737, height * 0.524)
        time.sleep(3)
        d.press('home')
        print("第四屏验证退出弹框和APL上限完成")
        demo_element = d(description="demo")
        demo_element.click()
        search_element1 = d(text=app_name)
        search_element1.click()
        search_element1.clear_text()
        d.press('home')
        url = "http://127.0.0.1:5000/stop_logging"
        response = requests.post(url)
